package mqtt;

import com.szh.common.constant.MQTTConstants;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

@Slf4j
public class SubscriptionMqttMsg {

    private static MqttClient client = null;

    static {
        try {
            MemoryPersistence persistence = new MemoryPersistence();

            client = new MqttClient(MQTTConstants.MQTT_BROKER_URL, MQTTConstants.SUBSCRIBER_MQTT_CLIENT_ID, persistence);
            // MQTT 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setUserName(MQTTConstants.mqtt_username);
            connOpts.setPassword(MQTTConstants.mqtt_pwd.toCharArray());
            // 保留会话
            connOpts.setCleanSession(true);

            client.connect(connOpts);
            log.info("连接成功");
            System.out.println("------------------");


        } catch (MqttException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws MqttException {
        // 设置回调
        client.setCallback(new OnMessageCallback());
        // 订阅
        client.subscribe(MQTTConstants.mqtt_subtopic_topic);
    }

    private static class OnMessageCallback implements MqttCallback {
        public void connectionLost(Throwable cause) {
            // 连接丢失后，一般在这里面进行重连
            System.out.println("连接断开，可以做重连");
        }

        public void messageArrived(String topic, MqttMessage message) throws Exception {
            // subscribe后得到的消息会执行到这里面
            System.out.println("接收消息主题:" + topic);
            System.out.println("接收消息Qos:" + message.getQos());
            System.out.println("接收消息内容:" + new String(message.getPayload()));
        }

        public void deliveryComplete(IMqttDeliveryToken token) {
            System.out.println("deliveryComplete---------" + token.isComplete());
        }
    }
}
